package com.hellojava.controller.api;

import com.hellojava.dto.OcrHistoryDto;
import com.hellojava.entity.OcrHistory;
import com.hellojava.service.OcrHistoryService;
import com.hellojava.util.ImageOcr;
import com.hellojava.util.WebUtil;
import com.hellojava.util.file.ConfigUtils;
import com.hellojava.util.file.FileUtils;
import com.hellojava.util.file.MetaData;
import com.hellojava.util.web.JsonResponse;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 *  识别图片
 * @author dengjihai
 * @create 2017-12-20
 **/
@RestController
@RequestMapping("/ocr")
public class OcrController {

    private Logger logger= LoggerFactory.getLogger(this.getClass());

    @Autowired
    OcrHistoryService ocrHistoryService;

    /**
     * 解析图片中的文字
     * @return
     */
    @PostMapping("/uploadImage")
    public JsonResponse ocrFiles(HttpServletRequest request, HttpServletResponse response, MultipartFile file)
            throws IOException {
        String openid = request.getParameter("openid");
        MetaData metaData = FileUtils.upload(file);
        metaData.setPath(ConfigUtils.fileHost+metaData.getPath());
        logger.info("\n 图片url："+metaData.getPath());
        JSONObject res=ImageOcr.normalParse(IOUtils.toByteArray(file.getInputStream()));
        JSONArray jsonArray=res.getJSONArray("words_result");
        logger.info("解析结果：{}",jsonArray.toString());
        HashMap<String,Object> map = new HashMap<>();
        map.put("result",jsonArray.toString());
        OcrHistoryDto ocrHistoryDto = new OcrHistoryDto();
        ocrHistoryDto.setContent(jsonArray.toString());
        if(res.getInt("words_result_num")>0){
            ocrHistoryDto.setTitle(((JSONObject)jsonArray.get(0)).getString("words"));
        }
        ocrHistoryDto.setLogId(String.valueOf(res.getLong("log_id")));
        ocrHistoryDto.setOpenId(openid);
        ocrHistoryDto.setImgUrl(metaData.getPath());
        ocrHistoryService.save(ocrHistoryDto);
        return WebUtil.successJsonResponse("解析成功",map);
    }


    @GetMapping("/user/list/{openId}")
    public JsonResponse getUserList(@PathVariable String openId){
        return WebUtil.successJsonResponse("获取历史记录成功",ocrHistoryService.getOcrHistoryByOpenId(openId));
    }

    @GetMapping("/history/info/{logId}")
    public JsonResponse getHistoryInfo(@PathVariable String logId){
        return WebUtil.successJsonResponse("获取历史记录明细成功",ocrHistoryService.getOcrHistoryByLogId(logId));
    }


}
